import Vue from "vue";
import VueRouter from "vue-router";
import { getToken } from "@/utils/storage";
Vue.use(VueRouter);

const routes = [
  {
    path: '/detail/:id',
    name: "Detail",
    component:()=>import("../views/Detail.vue")
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("../views/Login.vue"), //
  },
  {
    path: "/register",
    name: "register",
    component: () => import("../views/Register.vue"),
  },
  {
    path: "/",
    name: "Layout",
    redirect: "/article",
    component: () => import("../views/Layout.vue"),
    children: [
      {
        path: "/article",
        name: "Article",
        component: () => import("../views/Article.vue"),
      },
      {
        path: "/collect",
        name: "Collect",
        component: () => import("../views/Collect.vue"),
      },
      {
        path: "/like",
        name: "Like",
        component: () => import("../views/Like.vue"),
      },
      {
        path: "/my",
        name: "My",
        component: () => import("../views/My.vue"),
      },
    ],
  },
  // {
  //   path: '/about',
  //   name: 'About',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   /*  */
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')//路由懒加载
  // }
];

const router = new VueRouter({
  routes,
});

const white = ["/login", "/register"];

router.beforeEach((to, from, next) => {
  var token = getToken();

  if (token) {
    // console.log(token, "11token");
    next();
  } else {
    // console.log(token, "222token");
    if (white.includes(to.path)) {
      next();
    } else {
      next("/login");
    }
  }

});

let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;
VueRouter.prototype.push = function (location, res, rej) {
  if (res && rej) {
    originPush.call(this, location, res, rej);
  } else {
    originPush.call(
      this,
      location,
      () => { },
      () => { }
    );
  }
};

VueRouter.prototype.replace = function (location, res, rej) {
  if (res && rej) {
    originReplace.call(this, location, res, rej);
  } else {
    originReplace.call(
      this,
      location,
      () => { },
      () => { }
    );
  }
};

export default router;
